<?php 
namespace app\common\controller;

use app\common\model\trade\TradeCoinBuy;
use app\common\model\trade\TradeCoinSales;
use app\common\model\coin\CoinUser;
use think\Db;
use think\Exception;

class Trade
{
	/**
	 * 买入匹配
	 * @param unknown $id
	 * @param unknown $user_id
	 */
	public static function buyMate( $id , $user_id )
	{
		//获取当前买入委托信息
		$buy_info = TradeCoinBuy::get( $id );
		if($buy_info -> style == 1) {
			//限价买入
			self::limitBuy($id, $user_id);
		}
		//获取最新行情
		//$marcket = new Marcketline();
		//$close = $marcket ->getSymbolClose($buy_info->trans_pair);
	}
	public function saleMate($id , $user_id)
	{
		//获取当前买入委托信息
		$sale_info = TradeCoinSales::get( $id );
		if($sale_info -> style == 1) {
			//限价买入
			self::limitSale($id, $user_id);
		}
	}
	
	/**
	 * 匹配卖出订单
	 * @param int $buy_id 买入ID
	 * @param int $user_id 买入用ID
	 * @param number $page 页码
	 * @param number $surplus 匹配到的数量
	 * @param array $sale 卖出数据
	 * @param array $sale_user 卖出用户数组
	 */
	public function limitSale($buy_id,$user_id,$page = 1,$surplus = 0 , $sale = [],$sale_user = [])
	{
		$buy_info = TradeCoinSales::get($buy_id);
		$where = ['user_id' => ['neq',$user_id],'state' => 1];
		//所有数目
		$sale_count = TradeCoinBuy::where($where)->count();
		//每页查询条数
		$page_size = 15;
		//获取总页数
		$last_page = ceil($sale_count / $page_size);
		//每页起始数量
		$page_start = $page_size * ($page - 1);
		//获取别人的买入委托，按时间顺序
		$sale_list = TradeCoinBuy::where($where)->order('id asc')->limit($page_start,$page_size)->select();
		//判断是否可执行递归
		if($buy_info->surplus_num <= 0 || $buy_info->surplus_num == $surplus || !$sale_list || $page > $last_page) {
			Db::startTrans();
			try {
				//递归结束，计算逻辑
				$trade_sale = new TradeCoinBuy();
				$trade_sale -> saveAll($sale);  //更新卖出订单数量
				//更新买入订单
				$surplus_num = $buy_info->surplus_num - $surplus;
				$state = $surplus_num > 0 ? $buy_info->state : 2;
				$buy_info -> save(['surplus_num' => $surplus_num ,'state' => $state]);
				//更新买入用户的账户
				CoinUser::where(['user_id' => $user_id , 'coin_id' => $buy_info -> base_currency])->setDec('avalible_price',$surplus);
				CoinUser::where(['user_id' => $user_id , 'coin_id' => $buy_info -> quote_currency])->setInc('freezing_price',$surplus);
				//更新卖出用户的账户
				$coin_user = new CoinUser();
				$coin_user->isUpdate()->saveAll($sale_user);
				Db::commit();
			} catch (Exception $e) {
				Db::rollback();
				dump($e->getMessage());
			}
			
		} else {
			foreach ($sale_list as $val) {
				if($buy_info->sale_price == $val['buy_price'] && $buy_info->surplus_num > 0) {  //匹配到相同价格
					//判断买入与卖出的数量大小，判断需要操作的数量
					$num = $val['surplus_num'] >= $buy_info->surplus_num ? $buy_info->surplus_num : $val['surplus_num'];
					//计算出每个匹配出售订单剩余数量
					$sale_surplus = $val['surplus_num'] - $num;
					$sale[] = [
							'id' => $val['id'],
							'surplus_num' => $sale_surplus,
							'state' => $sale_surplus > 0 ? $val['state'] : 2
					];
					$sale_user = [
							'user_id' => $val['user_id'],
							'coin_id' => $val['quote_currency'],
							'freezing_price' => Db::raw("freezing_price - {$num}")
					];
					//计算出该买入订单所有匹配到的金额
					$surplus += $num;
				}
			}
			//递归调用自己，页码加一
			$page ++;
			self::limitSale($buy_id, $user_id,$page,$surplus,$sale);
		}
	}
	/**
	 * 匹配买入订单
	 * @param int $buy_id 买入ID
	 * @param int $user_id 买入用ID
	 * @param number $page 页码
	 * @param number $surplus 匹配到的数量
	 * @param array $sale 卖出数据
	 * @param array $sale_user 卖出用户数组
	 */
	public static function limitBuy($buy_id,$user_id,$page = 1,$surplus = 0 , $sale = [],$sale_user = [])
	{
		$buy_info = TradeCoinBuy::get($buy_id);
		$where = ['user_id' => ['neq',$user_id],'state' => 1];
		//所有数目
		$sale_count = TradeCoinSales::where($where)->count();
		//每页查询条数
		$page_size = 15;
		//获取总页数
		$last_page = ceil($sale_count / $page_size);
		//每页起始数量
		$page_start = $page_size * ($page - 1);
		//获取别人的卖出委托，按时间顺序
		$sale_list = TradeCoinSales::where($where)->order('id asc')->limit($page_start,$page_size)->select();
		//判断是否可执行递归
		if($buy_info->surplus_num <= 0 || $buy_info->surplus_num == $surplus || !$sale_list || $page > $last_page) {
			Db::startTrans();
			try {
				//递归结束，计算逻辑
				$trade_sale = new TradeCoinSales();
				$trade_sale -> saveAll($sale);  //更新卖出订单数量
				//更新买入订单
				$surplus_num = $buy_info->surplus_num - $surplus;
				$state = $surplus_num > 0 ? $buy_info->state : 2;
				$buy_info -> save(['surplus_num' => $surplus_num ,'state' => $state]);
				//更新买入用户的账户
				CoinUser::where(['user_id' => $user_id , 'coin_id' => $buy_info -> base_currency])->setInc('avalible_price',$surplus);
				CoinUser::where(['user_id' => $user_id , 'coin_id' => $buy_info -> quote_currency])->setDec('freezing_price',$surplus);
				//更新卖出用户的账户
				$coin_user = new CoinUser();
				$coin_user->isUpdate()->saveAll($sale_user);
				Db::commit();
			} catch (Exception $e) {
				Db::rollback();
				dump($e->getMessage());
			}
			
		} else {
			foreach ($sale_list as $val) {
				if($buy_info->buy_price == $val['sale_price'] && $buy_info->surplus_num > 0) {  //匹配到相同价格
					//判断买入与卖出的数量大小，判断需要操作的数量
					$num = $val['surplus_num'] >= $buy_info->surplus_num ? $buy_info->surplus_num : $val['surplus_num'];
					//计算出每个匹配出售订单剩余数量
					$sale_surplus = $val['surplus_num'] - $num;
					$sale[] = [
							'id' => $val['id'],
							'surplus_num' => $sale_surplus,
							'state' => $sale_surplus > 0 ? $val['state'] : 2
					];
					$sale_user = [
							'user_id' => $val['user_id'],
							'coin_id' => $val['base_currency'],
							'freezing_price' => Db::raw("freezing_price - {$num}")
					];
					//计算出该买入订单所有匹配到的金额
					$surplus += $num;
				}
			}
			//递归调用自己，页码加一
			$page ++;
			self::limitBuy($buy_id, $user_id,$page,$surplus,$sale);
		}
		
	}
}